"use client"; // 标记为客户端组件

import { useState, useEffect } from "react";
import { PlayCircle, PauseCircle, SkipBack, SkipForward, Heart } from "lucide-react";
import { VmsMusic } from "@/types/Model";

export default function MusicPlayer() {
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentMusic, setCurrentMusic] = useState<VmsMusic>({
    id: "",
    title: "",
    audio_url: "",
    music_type: ""
  });
  const [musicList, setMusicList] = useState<VmsMusic[]>([]);
  const [selectedCategory, setSelectedCategory] = useState("科技数码");
  const categories = [
    // "全部",
    "科技数码",
    "知识教程", 
    "美食手工",
    "旅行探险",
    "游戏解说",
    "Vlog",
    "纪录片",
    "微电影",
    "宣传片",
  ];

  useEffect(() => {
    const fetchMusic = async () => {
      try {
        const response = await fetch('/api/music');
        const data = await response.json();
        // 按score从高到低排序
        const sortedData = data.sort((a: VmsMusic, b: VmsMusic) => (b.score || 0) - (a.score || 0));
        setMusicList(sortedData);
        if (sortedData.length > 0) {
          setCurrentMusic(sortedData[0]);
        }
      } catch (error) {
        console.error('Failed to fetch music:', error);
      }
    };

    fetchMusic();
  }, []);

  const handleLike = async (musicId: string) => {
    try {
      const response = await fetch(`/api/music/like/${musicId}`, {
        method: 'POST'
      });
      const updatedMusic = await response.json();
      
      // 更新音乐列表中的点赞数
      setMusicList(prev => 
        prev.map(music => 
          music.id === updatedMusic.id 
            ? {...music, score: updatedMusic.score} 
            : music
        )
      );
      
      // 如果当前播放的音乐被点赞，更新当前音乐状态
      if (currentMusic.id === updatedMusic.id) {
        setCurrentMusic(updatedMusic);
      }
    } catch (error) {
      console.error('Failed to like music:', error);
    }
  };

  const playMusic = (item: VmsMusic) => {
    setCurrentMusic(item);
    setIsPlaying(true);
    const audio = document.getElementById("myAudio") as HTMLAudioElement;
    audio.src = item.audio_url || '';
    audio.play();
  };

  const pauseMusic = () => {
    setIsPlaying(false);
    const audio = document.getElementById("myAudio") as HTMLAudioElement;
    audio.pause();
  };

  const nextMusic = () => {
    const currentIndex = musicList.findIndex((music) => music.id === currentMusic.id);
    const nextIndex = (currentIndex + 1) % musicList.length;
    playMusic(musicList[nextIndex]);
  };

  const prevMusic = () => {
    const currentIndex = musicList.findIndex((music) => music.id === currentMusic.id);
    const prevIndex = (currentIndex - 1 + musicList.length) % musicList.length;
    playMusic(musicList[prevIndex]);
  };

  const filteredMusicList = selectedCategory === "全部" 
    ? musicList 
    : musicList.filter(music => music.theme === selectedCategory);

  return (
    <div className="w-full h-screen flex flex-col">
      <div className="flex-1 p-8 overflow-y-auto">
        <div className="max-w-7xl mx-auto">
          {/* 搜索框 */}
          <input
            type="search"
            placeholder="搜索音乐"
            className="w-full h-10 rounded-md border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          />

          {/* 分类筛选 */}
          <div className="mt-4 flex flex-wrap gap-2">
            {categories.map(category => (
              <button
                key={category}
                onClick={() => setSelectedCategory(category)}
                className={`px-4 py-2 rounded-full text-sm ${
                  selectedCategory === category
                    ? 'bg-blue-500 text-white'
                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
              >
                {category}
              </button>
            ))}
          </div>

          {/* 音乐列表 */}
          <div className="mt-6 space-y-4">
            {filteredMusicList.map((item) => (
              <div
                key={item.id}
                className="flex items-center justify-between p-4 bg-white rounded-lg shadow-sm hover:bg-gray-50 cursor-pointer"
                onClick={() => playMusic(item)}
              >
                <div className="flex items-center space-x-4">
                  {item.id === currentMusic.id && isPlaying ? (
                    <PauseCircle className="h-5 w-5 text-gray-600" />
                  ) : (
                    <PlayCircle className="h-5 w-5 text-gray-600" />
                  )}
                  <div className="flex flex-col min-w-0">
                    <span className="text-sm font-medium truncate">{item.title}</span>
                    <div className="flex items-center gap-2 flex-wrap">
                      {item.music_type && (
                        <span className="text-xs text-gray-500 bg-gray-100 px-2 py-1 rounded-full">
                          {item.music_type}
                        </span>
                      )}
                      {item.tags && (
                        <span className="text-xs text-gray-500 bg-gray-100 px-2 py-1 rounded-full">
                          {item.tags}
                        </span>
                      )}
                      <span className="text-xs text-gray-500 flex items-center gap-1">
                        <Heart className="w-3 h-3" />
                        {item.score || 0}
                      </span>
                    </div>
                  </div>
                </div>
                <button 
                  onClick={(e) => {
                    e.stopPropagation(); // 阻止事件冒泡
                    handleLike(item.id);
                  }}
                  className="p-1 hover:bg-gray-100 rounded-full"
                >
                  <Heart className="w-5 h-5 text-gray-600 hover:text-red-500" />
                </button>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* 播放控制栏 */}
      <div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200">
        <div className="max-w-7xl mx-auto p-4 flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <button onClick={prevMusic} className="p-2 hover:bg-gray-100 rounded-full">
              <SkipBack className="h-6 w-6 text-gray-600" />
            </button>
            <button
              onClick={isPlaying ? pauseMusic : () => playMusic(currentMusic)}
              className="p-2 hover:bg-gray-100 rounded-full"
            >
              {isPlaying ? (
                <PauseCircle className="h-8 w-8 text-gray-600" />
              ) : (
                <PlayCircle className="h-8 w-8 text-gray-600" />
              )}
            </button>
            <button onClick={nextMusic} className="p-2 hover:bg-gray-100 rounded-full">
              <SkipForward className="h-6 w-6 text-gray-600" />
            </button>
          </div>
          <div className="flex-1 text-center">
            <p className="text-lg font-bold truncate">{currentMusic.title}</p>
            <p className="text-sm text-gray-500">{currentMusic.music_type}</p>
          </div>
          <audio id="myAudio" className="w-64" controls>
            <source src={currentMusic.audio_url || ''} type="audio/mpeg" />
          </audio>
        </div>
      </div>
    </div>
  );
}